/*
 * This file is part of quickLoad, a software for gamers
 *
 * Copyright (C) 2005-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Collections.Specialized;
using GA_ScreenScraper;

namespace QuickLoad.UI
{
	/// <summary>
	/// Zusammenfassung fr FormUploadData.
	/// </summary>
	public class FormUploadData : System.Windows.Forms.Form
	{
		internal bool loggedin = false;
		internal Cookie cookie = null;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.Button button1;
		public System.Windows.Forms.TextBox tbPassword;
		private System.Windows.Forms.PictureBox pictureBox1;
		internal System.Windows.Forms.CheckBox saveLogin;
        private System.Windows.Forms.ImageList imageList1;
        internal System.Windows.Forms.ComboBox tbMatch;
        internal ComboBox cbAequitas;
        private PictureBox pictureBox2;
        private RadioButton rbCookie;
        internal RadioButton rbLogin;
        private Button bSelectCookie;
        private Label lLoggedIn;
        private ImageList imageList2;
        private Label label1;
        public TextBox tbUsername;
		private System.ComponentModel.IContainer components;

		public FormUploadData()
		{
			//
			// Erforderlich fr die Windows Form-Designeruntersttzung
			//
			InitializeComponent();
			LoadRecentMatches();
			//LoadRecentUsers();
			//
			// TODO: Fgen Sie den Konstruktorcode nach dem Aufruf von InitializeComponent hinzu
			//
		}

		private void SaveUserData(string Username, string Password, Cookie cook)
		{
			//
		}

		private void LoadUserData(ref string Username, ref string Password, ref Cookie cook)
		{
			//
		}

		private void LoadRecentMatches()
		{
		    tbMatch.Items.Clear();
		    foreach (string s in QuickLoad.Properties.Settings.Default.RecentMatches)
		    {
                this.tbMatch.Items.Add(s);
		    }
		}
		private void SaveRecentMatches()
		{
			//StreamWriter rm = new StreamWriter(@"Settings\RecentMatches.conf",false);
		    QuickLoad.Properties.Settings.Default.RecentMatches.Clear();
			foreach (object item in tbMatch.Items)
			{
				//rm.WriteLine(item.ToString());
                QuickLoad.Properties.Settings.Default.RecentMatches.Add(item.ToString());
			}
			//rm.Close();
		}
		/*private void LoadRecentUsers()
		{
            tbUsername.Items.Clear();
            foreach (string s in QuickLoad.Properties.Settings.Default.RecentUsers)
            {
                tbUsername.Items.Add(s);
            }
		    if (tbUsername.Items.Count > 0)
			{
				tbUsername.Text = tbUsername.Items[0].ToString();
			}
		}
		private void SaveRecentUsers()
		{
            QuickLoad.Properties.Settings.Default.RecentUsers.Clear();
            foreach (object item in tbUsername.Items)
            {
                //rm.WriteLine(item.ToString());
                QuickLoad.Properties.Settings.Default.RecentUsers.Add(item.ToString());
            }
		}
        */
		/// <summary>
		/// Die verwendeten Ressourcen bereinigen.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			SaveRecentMatches();
			//SaveRecentUsers();
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Vom Windows Form-Designer generierter Code
		/// <summary>
		/// Erforderliche Methode fr die Designeruntersttzung. 
		/// Der Inhalt der Methode darf nicht mit dem Code-Editor gendert werden.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormUploadData));
            this.tbPassword = new System.Windows.Forms.TextBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.cbAequitas = new System.Windows.Forms.ComboBox();
            this.tbMatch = new System.Windows.Forms.ComboBox();
            this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.tbUsername = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.bSelectCookie = new System.Windows.Forms.Button();
            this.rbCookie = new System.Windows.Forms.RadioButton();
            this.rbLogin = new System.Windows.Forms.RadioButton();
            this.saveLogin = new System.Windows.Forms.CheckBox();
            this.button1 = new System.Windows.Forms.Button();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.lLoggedIn = new System.Windows.Forms.Label();
            this.imageList2 = new System.Windows.Forms.ImageList(this.components);
            this.groupBox1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            this.groupBox2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // tbPassword
            // 
            this.tbPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tbPassword.Location = new System.Drawing.Point(40, 123);
            this.tbPassword.Name = "tbPassword";
            this.tbPassword.PasswordChar = '*';
            this.tbPassword.Size = new System.Drawing.Size(251, 20);
            this.tbPassword.TabIndex = 2;
            this.tbPassword.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tbUsername_KeyDown);
            // 
            // groupBox1
            // 
            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox1.Controls.Add(this.pictureBox2);
            this.groupBox1.Controls.Add(this.cbAequitas);
            this.groupBox1.Controls.Add(this.tbMatch);
            this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.groupBox1.Location = new System.Drawing.Point(3, 12);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(456, 72);
            this.groupBox1.TabIndex = 3;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "ESL-Matchlink (e.g. http://www.esl.eu/de/cs/2on2/ladder/match/1111111/)";
            // 
            // pictureBox2
            // 
            this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.pictureBox2.Cursor = System.Windows.Forms.Cursors.Help;
            this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
            this.pictureBox2.Location = new System.Drawing.Point(414, 19);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(32, 32);
            this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox2.TabIndex = 3;
            this.pictureBox2.TabStop = false;
            this.pictureBox2.Click += new System.EventHandler(this.pictureBox2_Click);
            // 
            // cbAequitas
            // 
            this.cbAequitas.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.cbAequitas.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbAequitas.Location = new System.Drawing.Point(3, 40);
            this.cbAequitas.Name = "cbAequitas";
            this.cbAequitas.Size = new System.Drawing.Size(405, 21);
            this.cbAequitas.TabIndex = 2;
            this.cbAequitas.TabStop = false;
            this.cbAequitas.SelectionChangeCommitted += new System.EventHandler(this.cbAequitas_SelectionChangeCommitted);
            this.cbAequitas.DropDown += new System.EventHandler(this.cbAequitas_DropDown);
            // 
            // tbMatch
            // 
            this.tbMatch.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tbMatch.Location = new System.Drawing.Point(3, 13);
            this.tbMatch.Name = "tbMatch";
            this.tbMatch.Size = new System.Drawing.Size(405, 21);
            this.tbMatch.TabIndex = 0;
            // 
            // imageList1
            // 
            this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList1.Images.SetKeyName(0, "");
            this.imageList1.Images.SetKeyName(1, "");
            this.imageList1.Images.SetKeyName(2, "Help.ico");
            // 
            // groupBox2
            // 
            this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox2.Controls.Add(this.tbUsername);
            this.groupBox2.Controls.Add(this.label1);
            this.groupBox2.Controls.Add(this.bSelectCookie);
            this.groupBox2.Controls.Add(this.rbCookie);
            this.groupBox2.Controls.Add(this.rbLogin);
            this.groupBox2.Controls.Add(this.saveLogin);
            this.groupBox2.Controls.Add(this.tbPassword);
            this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.groupBox2.Location = new System.Drawing.Point(3, 90);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(318, 188);
            this.groupBox2.TabIndex = 4;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Benutzerdaten";
            // 
            // tbUsername
            // 
            this.tbUsername.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tbUsername.Location = new System.Drawing.Point(40, 96);
            this.tbUsername.Name = "tbUsername";
            this.tbUsername.Size = new System.Drawing.Size(251, 20);
            this.tbUsername.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(40, 144);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(272, 39);
            this.label1.TabIndex = 7;
            this.label1.Text = "Hinweis: Es werden keine Benutzerdaten gespeichert, sondern nur das Login-Cookie," +
                " welches keine Rckschlsse auf Benutzernamen oder Passwort erlaubt.";
            // 
            // bSelectCookie
            // 
            this.bSelectCookie.Location = new System.Drawing.Point(40, 42);
            this.bSelectCookie.Name = "bSelectCookie";
            this.bSelectCookie.Size = new System.Drawing.Size(110, 23);
            this.bSelectCookie.TabIndex = 6;
            this.bSelectCookie.Text = "Cookie auswhlen";
            this.bSelectCookie.UseVisualStyleBackColor = true;
            this.bSelectCookie.Click += new System.EventHandler(this.bSelectCookie_Click);
            // 
            // rbCookie
            // 
            this.rbCookie.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.rbCookie.Location = new System.Drawing.Point(6, 21);
            this.rbCookie.Name = "rbCookie";
            this.rbCookie.Size = new System.Drawing.Size(252, 24);
            this.rbCookie.TabIndex = 3;
            this.rbCookie.TabStop = true;
            this.rbCookie.Text = "Benutze vorhandenes Cookie (empfohlen)";
            this.rbCookie.UseVisualStyleBackColor = true;
            // 
            // rbLogin
            // 
            this.rbLogin.Location = new System.Drawing.Point(6, 73);
            this.rbLogin.Name = "rbLogin";
            this.rbLogin.Size = new System.Drawing.Size(252, 17);
            this.rbLogin.TabIndex = 4;
            this.rbLogin.TabStop = true;
            this.rbLogin.Text = "Benutzernamen und Passwort selber eingeben:";
            this.rbLogin.UseVisualStyleBackColor = true;
            this.rbLogin.CheckedChanged += new System.EventHandler(this.rbLogin_CheckedChanged);
            // 
            // saveLogin
            // 
            this.saveLogin.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.saveLogin.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.saveLogin.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.saveLogin.Location = new System.Drawing.Point(192, 166);
            this.saveLogin.Name = "saveLogin";
            this.saveLogin.Size = new System.Drawing.Size(120, 16);
            this.saveLogin.TabIndex = 3;
            this.saveLogin.Text = "Remember password";
            this.saveLogin.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            this.saveLogin.Visible = false;
            this.saveLogin.CheckedChanged += new System.EventHandler(this.saveLogin_CheckedChanged);
            // 
            // button1
            // 
            this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
            this.button1.Location = new System.Drawing.Point(327, 90);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(132, 36);
            this.button1.TabIndex = 4;
            this.button1.TabStop = false;
            this.button1.Text = "OK ";
            // 
            // pictureBox1
            // 
            this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
            this.pictureBox1.Location = new System.Drawing.Point(327, 132);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(132, 106);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox1.TabIndex = 6;
            this.pictureBox1.TabStop = false;
            // 
            // lLoggedIn
            // 
            this.lLoggedIn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lLoggedIn.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lLoggedIn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.lLoggedIn.ImageIndex = 1;
            this.lLoggedIn.ImageList = this.imageList2;
            this.lLoggedIn.Location = new System.Drawing.Point(327, 241);
            this.lLoggedIn.Name = "lLoggedIn";
            this.lLoggedIn.Size = new System.Drawing.Size(132, 37);
            this.lLoggedIn.TabIndex = 7;
            this.lLoggedIn.Text = "Nicht Eingeloggt";
            this.lLoggedIn.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // imageList2
            // 
            this.imageList2.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList2.ImageStream")));
            this.imageList2.TransparentColor = System.Drawing.Color.Transparent;
            this.imageList2.Images.SetKeyName(0, "Checked_24.ico");
            this.imageList2.Images.SetKeyName(1, "X_24.ico");
            // 
            // FormUploadData
            // 
            this.AcceptButton = this.button1;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(461, 282);
            this.Controls.Add(this.lLoggedIn);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.pictureBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "FormUploadData";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Enter Login-Data and Match-Info";
            this.Closed += new System.EventHandler(this.FormUploadData_Closed);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.FormUploadData_Closing);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormUploadData_FormClosing);
            this.Load += new System.EventHandler(this.FormUploadData_Load);
            this.groupBox1.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion

		private void FormUploadData_Load(object sender, System.EventArgs e)
		{
            if ((QuickLoad.Properties.Settings.Default.Cookie != string.Empty && QuickLoad.Properties.Settings.Default.LoggedIn))
                rbLogin.Checked = true;
            else
                rbCookie.Checked = true;
            rbLogin_CheckedChanged(null, null);

            SetLoggedIn(QuickLoad.Properties.Settings.Default.Cookie != string.Empty);
        }

        string URLDecode(string input)
        {
            input = input.Replace("%3A", ":");
            input = input.Replace("%7Bs", "{");
            input = input.Replace("%22", "\"");
            input = input.Replace("%3B", ";");
            input = input.Replace("%7D", "}");
            return input;
        }
        string CookieDecoder = "\"id\";s:\\d+:\"(\\d+)\".*\"pw\";s:32:\"(\\w{32})\";}";

        private void SetLoggedIn(bool status)
        {
            if (status)
            {
                lLoggedIn.BorderStyle = BorderStyle.Fixed3D;
                lLoggedIn.ImageIndex = 0;
                lLoggedIn.Text = "Eingeloggt als:" + Environment.NewLine + Regex.Match(URLDecode(QuickLoad.Properties.Settings.Default.Cookie),CookieDecoder).Groups[1].Value;
                button1.Enabled = true;
            }
            else
            {
                lLoggedIn.BorderStyle = BorderStyle.None;
                lLoggedIn.ImageIndex = 1;
                lLoggedIn.Text = "Nicht Eingeloggt";
                if (rbLogin.Checked && tbUsername.Text != String.Empty && tbPassword.Text != String.Empty)
                    button1.Enabled = true;
                else
                    button1.Enabled = false;
            }
        }

		private void tbMatch_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
		}

		private void FormUploadData_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if ((this.DialogResult == DialogResult.OK) && (!System.Text.RegularExpressions.Regex.Match(tbMatch.Text,@"^http://www.esl.eu/.+?/match/\d+?/*$").Success))
			{
				e.Cancel = true;
				MessageBox.Show("The Matchlink you entered has a wrong format, it should look like this:\nhttp://www.esl.eu/**************/match/1111111/", "Invalid Matchlink");
			}
		}

		private void FormUploadData_Closed(object sender, System.EventArgs e)
		{
			if (this.DialogResult == DialogResult.OK)
			{
				if (tbMatch.Text != string.Empty && !(tbMatch.Items.IndexOf(tbMatch.Text) == 0))
				{
					tbMatch.Items.Insert(0,tbMatch.Text);
				}
				/*if (tbUsername.Text != string.Empty && !(tbUsername.Items.IndexOf(tbUsername.Text) == 0))
				{
					tbUsername.Items.Insert(0,tbUsername.Text);
				}*/
				if (tbMatch.Items.Count > 10)
				{
					tbMatch.Items.RemoveAt(tbMatch.Items.Count-1);
				}
				/*if (tbUsername.Items.Count > 10)
				{
					tbUsername.Items.RemoveAt(tbUsername.Items.Count-1);
				}*/
			}
		    SaveRecentMatches();
		    //SaveRecentUsers();
		}

		private void saveLogin_CheckedChanged(object sender, System.EventArgs e)
		{
			if (!saveLogin.Checked)
			{
				tbUsername.Enabled=true;
				tbPassword.Enabled=true;
			}
		}
	    private const int CB_GETCOUNT = 0x146;
        private const int CB_GETLBTEXT = 0x148;
        private const int CB_GETCURSEL = 0x147;
        private const int CB_GETLBTEXTLEN = 0x149;
        private const int CB_SELECTSTRING = 0x14D;
        private const int CB_SHOWDROPDOWN = 0x14F;
        private const int CBN_SELENDOK = 0x9;
        private const int CBN_SELCHANGE = 1;
        private const int CBN_SETFOCUS = 3;
        private const int CBN_KILLFOCUS = 4;
        private const int CBN_EDITCHANGE = 5;
        private const int CBN_EDITUPDATE = 6;
        private const int CBN_DROPDOWN = 7;
        private const int CBN_CLOSEUP = 8;
        private const int CB_SETCURSEL = 0x14E;
        private const int WM_COMMAND = 0x0111;
        private GA_ScreenScraper.ScreenScraper aeq;
        private void button2_Click(object sender, EventArgs e)
        {
            bool aeqrunning = true;
            cbAequitas.Items.Clear();
            
            aeq = new GA_ScreenScraper.ScreenScraper("ESL Aequitas *beta*", "ThunderRT6FormDC");
            try
            {
                aeq.GetControlContent("ThunderRT6ComboBox");
            }
            catch
            {
                //MessageBox.Show("Aequitas not running - could not get info");
                cbAequitas.Items.Add(QuickLoad.lang.AequitasNotRunning);
                cbAequitas.SelectedItem = cbAequitas.Items[cbAequitas.Items.Count-1];
                aeqrunning = false;
            }
            if (aeqrunning)
            {
                int ComboCount = (int)Win32.SendMessage(aeq.ChildWindowPtr, CB_GETCOUNT, IntPtr.Zero, IntPtr.Zero);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < ComboCount; i++)
                {
                    int strlen = (int)Win32.SendMessage(aeq.ChildWindowPtr, CB_GETLBTEXTLEN, new IntPtr(i), IntPtr.Zero);
                    StringBuilder result = new StringBuilder(strlen);
                    strlen = (int)Win32.SendMessage(aeq.ChildWindowPtr, CB_GETLBTEXT, new IntPtr(i), result);
                    cbAequitas.Items.Add(result.ToString());
                    sb.AppendLine(result.ToString());
                }
            }
        }

        private void cbAequitas_SelectionChangeCommitted(object sender, EventArgs e)
        {
            

            //get current handle
            try
            {
                aeq.GetControlContent("ThunderRT6ComboBox");
            }
            catch
            {
                cbAequitas.Items.Clear();
                cbAequitas.Items.Add(QuickLoad.lang.AequitasNotRunning);
                cbAequitas.SelectedItem = cbAequitas.Items[cbAequitas.Items.Count - 1];
                return;
            }
            //string link = aeq.GetControlContent("ThunderRT6TextBox");
            int index = (int)Win32.SendMessage(aeq.ChildWindowPtr, CB_GETCURSEL, IntPtr.Zero, IntPtr.Zero);
            StringBuilder old=null;
            if(index >= 0)
            {
                old = new StringBuilder((int)Win32.SendMessage(aeq.ChildWindowPtr, CB_GETLBTEXTLEN, new IntPtr(index), IntPtr.Zero));
                Win32.SendMessage(aeq.ChildWindowPtr, CB_GETLBTEXT, new IntPtr(index), old);
            }
            SelectString(cbAequitas.Text.Trim());
            string MatchURL = aeq.GetControlContent("ThunderRT6TextBox");
            while (MatchURL[MatchURL.Length - 1].ToString() != "/" && !Regex.Match(MatchURL[MatchURL.Length - 1].ToString(), "\\d").Success)
                MatchURL = MatchURL.Remove(MatchURL.Length - 1);
            tbMatch.Text = MatchURL;
            if(index >= 0)
                SelectString(old.ToString());
            
            
        }
	    private void SelectString(string entry)
	    {
            StringBuilder sb = new StringBuilder(entry);
            aeq.GetControlContent("ThunderRT6ComboBox");
            //select preselected string
            Win32.SendMessage(aeq.ChildWindowPtr, CB_SELECTSTRING, new IntPtr(-1), sb);
            //set focus (not necessary?)
            machs(aeq, CBN_SETFOCUS);
            //make selection valid
            machs(aeq, CBN_EDITUPDATE);
            //fire selectionchanged-event
            machs(aeq, CBN_SELCHANGE);
	    }
	    private void machs(GA_ScreenScraper.ScreenScraper aeqq,int cmd)
	    {
	        //get current handle
            aeqq.GetControlContent("ThunderRT6ComboBox");
            Win32.SendMessage(aeqq.parentWindowHandle, WM_COMMAND, Win32.MakeLParam((int)Win32.GetDlgCtrlID(aeq.ChildWindowPtr), cmd), aeqq.ChildWindowPtr);
	    }

        private void cbAequitas_DropDown(object sender, EventArgs e)
        {
            button2_Click(sender,e);
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(QuickLoad.lang.MatchLinkHint);
        }

        private void rbLogin_CheckedChanged(object sender, EventArgs e)
        {
            
            if (rbLogin.Checked)
            {
                if (!QuickLoad.Properties.Settings.Default.LoggedIn)
                {
                    tbUsername.Enabled = true;
                    tbPassword.Enabled = true;
                    saveLogin.Checked = false;
                }
                else
                {
                    tbUsername.Enabled = false;
                    tbPassword.Enabled = false;
                    saveLogin.Checked = true;
                }
                saveLogin.Enabled = true;
                bSelectCookie.Enabled = false;
            }
            else
            {
                tbUsername.Enabled = false;
                tbPassword.Enabled = false;
                saveLogin.Enabled = false;
                bSelectCookie.Enabled = true;
                QuickLoad.Properties.Settings.Default.LoggedIn = false;
            }
            if (rbLogin.Checked)
                SetLoggedIn(!saveLogin.Enabled);
            else
                SetLoggedIn(QuickLoad.Properties.Settings.Default.Cookie != string.Empty && QuickLoad.Properties.Settings.Default.LoggedIn);
        }

        private void bSelectCookie_Click(object sender, EventArgs e)
        {
            using (FormCookieSelect f = new FormCookieSelect())
            {
                if (f.ShowDialog(this) == DialogResult.OK)
                    QuickLoad.Properties.Settings.Default.Cookie = f.Cookie;
                //else
                    //QuickLoad.Properties.Settings.Default.Cookie = String.Empty;
                SetLoggedIn(QuickLoad.Properties.Settings.Default.Cookie != string.Empty);
            }
        }

        private void FormUploadData_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(DialogResult == DialogResult.OK && rbLogin.Checked && tbUsername.Enabled)
            {
                string cook;
                if ((cook = getLoginCookie(tbUsername.Text,tbPassword.Text)) != String.Empty)
                {
                    QuickLoad.Properties.Settings.Default.Cookie = cook;
                    QuickLoad.Properties.Settings.Default.LoggedIn = true;
                }
                else
                {
                    DialogResult = DialogResult.None;
                    e.Cancel = true;
                }

            }
            if (!rbLogin.Checked)
                QuickLoad.Properties.Settings.Default.LoggedIn = false;
        }
        public string getLoginCookie(string Username, String Password)
        {
            string cookie = string.Empty;
            HttpWebRequest request = null;
            StreamReader answer = null;
            string HTML = String.Empty;
            try
            {
                request = (HttpWebRequest)WebRequest.Create("http://www.esl.eu/login/save/?duration=forever&email_id=" + Username + "&password=" + Password);
                request.CookieContainer = new CookieContainer();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                answer = new StreamReader(response.GetResponseStream());
                HTML = answer.ReadToEnd();
            }
            catch (Exception ex)
            {
                //AddLog(String.Format(m_Uploader.lang.GetString("LoginError",m_Uploader.culture),ex.Message));
                MessageBox.Show("Error!",ex.Message);
                return string.Empty;
            }
            finally
            {
                if (answer != null)
                    answer.Close();
            }
            if (Regex.Match(HTML, ">Logged in!<").Success)
            {
                cookie = request.CookieContainer.GetCookies(request.RequestUri)["COOKIE"].Value;
            }
            else
            {
                MessageBox.Show("Error!", "Username and/or password wrong or ESL-database offline!");
            }
            return cookie;
        }

        private void tbUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (tbUsername.Text != String.Empty)
                button1.Enabled = true;
        }
	}
}
